
import 'dart:ui';

import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/moment/publish.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/date.dart';
import 'package:fate_blind_box/utils/image.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/material.dart';

import '../../utils/default/Empty.dart';
import '../user/profile.dart';
import 'detail.dart';

class CycleListUi extends StatelessWidget {
  const CycleListUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _CycleListWidget();
  }
}

class _CycleListWidget extends StatefulWidget {
  const _CycleListWidget({Key? key}) : super(key: key);

  @override
  State<_CycleListWidget> createState() => _CycleListWidgetState();
}

class _CycleListWidgetState extends State<_CycleListWidget> with TickerProviderStateMixin {

  final _titles = ["红娘圈", "好友圈"];
  late TabController _tabController;
  late PageController _pageController;
  late double _screenWidth;
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _titles.length, vsync: this);
    _pageController = PageController();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels > _scrollController.position.maxScrollExtent - 20) {
        if (_tabController.index == 0) {
          _pageNum2++;
          _getMatcherList();
        } else {
          _pageNum++;
          _getListData();
        }
      }
    });
    _getMatcherList();
  }

  void _onTabChanged(int index) {
    _pageController.animateToPage(
        index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.ease
    );
  }

  void _onPageChanged(int index) {
    _tabController.animateTo(
        index,
        duration: const Duration(milliseconds: 300)
    );
    if (index == 1 && _listData.isEmpty) {
      _getListData();
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppWidget.statusBar(),
      backgroundColor: Colors.white,
      body: Column(
        children: [
          _buildTitleBar(),
          Expanded(child: _buildPageView())
        ],
      ),
    );
  }

  Widget _buildTitleBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      height: 56,
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(
            width: 56,
            child:AppWidget.leftArrowWidget(null),
          ),
          SizedBox(
            width: 200,
            child: _buildTabBar(),
          ),
          GestureDetector(
            onTap: () async{
              final result = await Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const CyclePublishUi()));
              if (result == 0 && _tabController.index == 1) {
                await _onRefresh(1);
              }
            },
            child: Container(
              height: 32,
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: ThemeColor.appColor
              ),
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: const Text("发布", style: TextStyle(color: Colors.white),),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildTabBar() {
    return TabBar(
      controller: _tabController,
      tabs: _titles.map((e) => Tab(text: e)).toList(),
      labelColor: ThemeColor.textColor,
      labelStyle: TextStyle(
          color: ThemeColor.textColor,
          fontWeight: FontWeight.bold,
          fontSize: 16
      ),
      unselectedLabelColor: ThemeColor.textColorSecond,
      unselectedLabelStyle: TextStyle(
          color: ThemeColor.textColorSecond,
          fontSize: 14
      ),
      isScrollable: false,
      indicatorColor: ThemeColor.appColor,
      indicatorSize: TabBarIndicatorSize.label,
      indicatorPadding: const EdgeInsets.symmetric(horizontal: 10),
      onTap: _onTabChanged,
    );
  }

  Widget _buildPageView() {
    return PageView.builder(
      controller: _pageController,
      // physics: const BouncingScrollPhysics(),
      itemCount: _titles.length,
      onPageChanged: _onPageChanged,
      itemBuilder: (context, index) {
        return _buildListView(index);
      },
    );
  }

  Future<void> _onRefresh(int type) async {
    if (type == 0) {
      _pageNum2 = 1;
      await _getMatcherList();
    } else {
      _pageNum = 1;
      await _getListData();
    }
  }

  Widget _buildListView(int position) {
    int itemCount = position == 0 ? _matcherListData.length : _listData.length;
    return RefreshIndicator(
      onRefresh: () async {
        await _onRefresh(position);
      },
      child: itemCount <= 0 ? const Empty() : ListView.builder(
          itemCount: itemCount,
          controller: _scrollController,
          itemBuilder: (context, index) {
            final itemData = position == 0 ? _matcherListData[index] : _listData[index];
            return _buildItemView(itemData);
          }
      ),
    );
  }

  Widget _buildItemView(itemData) {
    final urls = itemData['picUrls'];
    var images = urls == null || urls.isEmpty ? <String>[] : urls.split(',');
    return GestureDetector(
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (builder) => CycleDetailUi(data: itemData)));
      },
      child: Container(
        padding: const EdgeInsets.fromLTRB(12, 18, 12, 0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            GestureDetector(
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const UserProfileUi(memberId: "")));
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(20),
                child: AppImages.avatar(itemData['profilePhoto'], 40)
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    itemData['nickName']??"匿名用户",
                    style: TextStyle(
                        color: ThemeColor.textColor,
                        fontSize: 12
                    ),
                  ),
                  const SizedBox(height: 3,),
                  Text(
                    RelativeDateFormat.format(DateTime.parse(itemData['createTime'])),
                    style: TextStyle(
                        fontSize: 12,
                        color: ThemeColor.textColorSecond
                    ),
                  ),
                  const SizedBox(height: 8,),
                  Text(
                    itemData['content'],
                    style: TextStyle(
                        color: ThemeColor.textColor3,
                        fontSize: 12
                    ),
                  ),
                  const SizedBox(height: 10),
                  // TODO 照片
                  _buildPhoto(images),
                  const SizedBox(height: 12,),
                  _buildActions(itemData['likeCount'], itemData['commentCount'])
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildPhoto(List<String> photos) {
    if (photos.isEmpty) {
      return Container();
    }
    photos.removeWhere((element) => element.isEmpty);
    if (photos.length == 1) {
      return Container(
        margin: const EdgeInsets.only(top: 10),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Image.network(
            photos[0],
            width: _screenWidth - 76,
            height: (_screenWidth - 76) / 298* 204,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return _getErrorBuilder(_screenWidth - 76, (_screenWidth - 76) / 298* 204);
            },
          ),
        ),
      );
    }
    if (photos.length == 2) {
      double size = (_screenWidth - 82) / 2;
      return Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.network(
              photos[0],
              width: size,
              height: size,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return _getErrorBuilder(size, size);
              },
            ),
          ),
          const SizedBox(width: 6,),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.network(
              photos[1],
              width: size,
              height: size,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return _getErrorBuilder(size, size);
              },
            ),
          )
        ],
      );
    }
    double firSize =( _screenWidth - 82) / 73 * 49;
    double secSize = (firSize - 6) / 2;
    return SizedBox(
      height: firSize,
      child: Stack(
        children: [
          Align(
              alignment: Alignment.topLeft,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Image.network(
                  photos[0],
                  width: firSize,
                  height: firSize,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return _getErrorBuilder(firSize, firSize);
                  },
                ),
              )
          ),
          Align(
            alignment: Alignment.topRight,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Image.network(
                photos[1],
                width: secSize,
                height: secSize,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return _getErrorBuilder(secSize, secSize);
                },
              ),
            ),
          ),
          Align(
            alignment: Alignment.bottomRight,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Image.network(
                photos[2],
                width: secSize,
                height: secSize,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return _getErrorBuilder(secSize, secSize);
                },
              ),
            ),
          ),
          photos.length > 3 ? _buildPhotoCountTag(photos.length) : const SizedBox(width: 0, height: 0,)
        ],
      ),
    );
  }

  Widget _getErrorBuilder(double width, double height) {
    return Container(
      width: width,
      height: height,
      decoration: ShapeDecoration(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(4)
        ),
        color: const Color(0xFFF2F2F2)
      ),
      alignment: Alignment.center,
      child: Image.asset(
        "images/ic_error_place.png",
        width: width * 0.5,
        height: height * 0.5,
      ) ,
    );
  }

  Widget _buildPhotoCountTag(int count) {
    return Positioned(
      bottom: 6,
      right: 6,
      child: Container(
        decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4)
          ),
          color: Colors.black,
        ),
        height: 18,
        padding: const EdgeInsets.symmetric(horizontal: 4),
        alignment: Alignment.center,
        child: IconText(
          "  $count张",
          icon: const Icon(Icons.photo_library, size: 10, color: Colors.white,),
          style: const TextStyle(fontSize: 10, color: Colors.white),
        ),
      ),
    );
  }

  Widget _buildActions(int likeCount, int commentCount) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Expanded(child: Container()),
        IconText(
          "  $likeCount",
          icon: Icon(
            Icons.favorite, //favorite_outline
            color: ThemeColor.textColorSecond, //ThemeColor.mainColor,
            size: 18,
          ),
          style: TextStyle(
            color: ThemeColor.textColorSecond,
            fontSize: 13,
          ),
        ),
        const SizedBox(width: 10,),
        // IconText(
        //   "  $commentCount",
        //   style: TextStyle(
        //     color: ThemeColor.textColorSecond,
        //     fontSize: 13,
        //   ),
        //   icon: Icon(
        //     Icons.comment_outlined,
        //     color: ThemeColor.textColorSecond,
        //     size: 18,
        //   ),
        // )
      ],
    );
  }

  /// 获取列表数据
  final _listData = <dynamic>[];
  int _pageNum = 1;
  _getListData() async{
    final res = await Api.getInstance().getMoodList(Provider.memberId, _pageNum, 10);
    if (res['code'] == 0) {
      if (_pageNum <= 1) {
        _listData.clear();
      }
      final data = res['data'];
      if (data != null && data['list'] != null) {
        setState(() {
          _listData.addAll(data['list']);
        });
      }

    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  /// 获取红娘圈列表
  final _matcherListData = <dynamic>[];
  int _pageNum2 = 1;
  _getMatcherList() async {
    final res = await Api.getInstance().getMatchmakerMoods(_pageNum2);
    print(res);
  }
}


